<?php
class Admin_model extends MY_Model
{
	public
		$table = 'admins',
		$prKey = 'id',
		$publishedField = 'status',

		$status = array(
			'1' => 'Active',
			'2' => 'Blocked',
		)
	;

	function __construct()
	{
		parent::__construct();

		$this->fields = array(
			'id'		 		=> '',
			'password' 			=> T_('Password'),
			'new_password' 		=> T_('Password'),
			'password_confirm' 	=> T_('Re-enter Password'),
			'first_name' 		=> T_('First Name'),
			'last_name' 		=> T_('Last Name'),
			'email' 			=> T_('E-mail'),
			'date_created'		=> T_('Date created'),
			'date_modified'		=> T_('Date modified'),
			'forgot_user_login' => T_('E-mail'),
			'status' 			=> T_('Status'),
			'id_acl_roles' 		=> T_('User Role'),
			'activation_code' 	=> T_('Activation code'),
		);

		$this->rules = array(
			'first_name' 		=> "trim|required|max_length[255]",
			'last_name' 		=> "trim|required|max_length[255]",
			'email' 			=> "trim|required|valid_email|max_length[64]|callback___loginFree",
			'password' 			=> "trim|required|matches[password_confirm]|alpha_dash|min_length[6]|max_length[32]",
			'new_password' 		=> "trim|matches[password_confirm]|alpha_dash|min_length[6]|max_length[32]",
			'password_confirm' 	=> "trim|alpha_dash|min_length[6]|max_length[32]",
			'status' 			=> "trim|is_natural_no_zero",
			'id_acl_roles'		=> "trim|is_natural_no_zero",
			'activation_code' 	=> "trim|max_length[32]",
		);
	}

	function save($data)
	{
		if (isset($data['password']))
		{
			$data['password'] = $this->__cryptPassword($data['password']);
		}

		parent::save($data);
	}
	
	function loginFree($login = null)
	{
		$this->db->where('email', $login);
		
		if(!empty($this->id_admin))
		{
			$this->db->where('id !=', $this->id_admin);	
		}
		
		$query = $this->db->get($this->table);

		if (!$query->num_rows())
		{
			return true;
		}		
		
		return false;
	}
	
	function __cryptPassword($password = null)
	{
		return md5($password . SALT);	
	}
	
	function getByLoginPassword($login = null, $password = null)
	{
		$sql = "
			SELECT a.id, a.email, a.first_name, a.last_name, CONCAT(a.first_name, ' ', a.last_name) AS fullname, a.date_created, a.date_modified, a.status, a.id_acl_roles, r.name AS role
			FROM ".$this->table." a
			LEFT JOIN acl_roles r ON r.id=a.id_acl_roles
			WHERE a.email=".$this->db->escape($login)." AND a.password='".$this->__cryptPassword($password)."'";
		$query = $this->db->query($sql);
		
		if ($query->num_rows() === 1)
		{
			return $query->row_array();
		}
		
		return false;
	}

	function getByLogin($login = null)
	{
		$sql = "
			SELECT id, email, CONCAT(first_name, ' ', last_name) AS fullname, date_created, date_modified, status
			FROM ".$this->table."
			WHERE email=".$this->db->escape($login);
		$user = $this->db->query($sql)->row_array();
		
		if (!empty($user))
		{
			return $user;
		}
		
		return false;
	}
	
	function search($config = array())
	{
		$config = array_merge(array('rowsOnPage' => 5, 'order' => 'id'), $config);
		
		$order 		= $this->input->get_post('order');
		$direction 	= $this->input->get_post('direction');
		$search 	= $this->input->get_post('search');
		
		// main sql		
		$sql = '';
		$sql .= ' FROM '.$this->table.' u';
		$sql .= ' WHERE 1 = 1';  
								
		if ($search)
		{
			$sql .= ' AND u.fullname LIKE ' . $this->db->escape('%' . $search . '%'); 
		}
		
		switch ($order)
		{
			case 'date':
				$sql .= ' ORDER BY u.date_created'; 
				break;
			
			default:
				$sql .= ' ORDER BY u.id';
				$direction = 'DESC';
		}
		
		$sql .= ($direction == 'DESC') ? ' DESC' : ' ASC';
		
		// main sql
		$sql = 'SELECT *' . $sql; 

		$this->data['list'] = $this->db->query($sql)->result();
	}
	
	function delete($items_serialized = null)
	{
		$items = explode("&", $items_serialized);
		
		$report = "";
		foreach ($items as $id)
		{	
			$user_own_ID = $this->auth->getID();
			if ($user_own_ID == $id) // Delete own profile
			{
				$this->auth->logout();
			}
				
        	$data = $this->admin_model->get($id);
        
			$res = $this->db->delete($this->table, array($this->prKey => $id));
			
			if (is_null($res))
			{
				$this->log->writeMessage('error', T_('Error. Administrator was not removed.'));
				$report .= ",0"; // don't deleted
			}
			else
			{
				$this->log->writeMessage('done', T_('Administrator was removed.'));
				$report .= ",1"; // deleted					
			}	
		}
		
		return substr($report, 1);
	}
		
	function insert($data)
	{
		if (!empty($data))
		{
			if (isset($data['password']))
			{
				$data['password'] = $this->__cryptPassword($data['password']);
			}
	
			$data['date_created'] = date('Y-m-d H:i:s');
			$data['date_modified'] = date('Y-m-d H:i:s');			
			
			parent::insert($data);

			if ($this->db->insert_id() > 0)
			{
				$this->log->writeMessage('done', T_('Administrator was added succesfully.'));

				return TRUE;
			}
			else
			{
				$this->log->writeMessage('error', T_('Error! Administrator was not created.'));
				
				return FALSE;
			}
		}		
	}

	function update($data)
	{
		if (!empty($data))
		{
			if (isset($data['password']))
			{
				$data['password'] = $this->__cryptPassword($data['password']);
			}
	
			$data['date_modified'] = date('Y-m-d H:i:s');
				
			$res = parent::update($data);

			$this->log->writeMessage('done', T_('Saved succesfully.'));

			return TRUE;			
		}		
	}	
		
	function resetPasswordUser($code = '')
	{
		if(empty($code)) return FALSE;
		
		$sql = "SELECT id FROM ".$this->table." WHERE activation_code=".$this->db->escape($code);
		$user = $this->db->query($sql)->row();
		
		if (!empty($user))
		{
			$sql = "UPDATE ".$this->table." SET password=".$this->db->escape($code).", activation_code='' WHERE id=".$user->id;
			$this->db->query($sql);
			
			return TRUE;
		}
		else
		{
			return FALSE;
		}
	}
	
  	function activateUser($code = '')
	{
		if(empty($code)) return FALSE;
		
		$sql = "SELECT id FROM ".$this->table." WHERE activation_code=".$this->db->escape($code);
		$user = $this->db->query($sql)->row();
		
		if (!empty($user))
		{
			$sql = "UPDATE ".$this->table." SET status=".USER_STATUS_ACTIVE.", activation_code='' WHERE id=".$user->id;
			$this->db->query($sql);
			
			return TRUE;
		}
		else
		{
			return FALSE;
		}
	}	
	
}
?>